﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

using System.Data;
using Gift.DAL;
using Gift.Model;
using Gift.Model.ENUM;

namespace WebSite.admin.product
{
    public partial class openCardList : BaseAdmin
    {
        readonly dalCompany theCompany = new dalCompany();
        readonly DALCardState theCardState = new DALCardState();
        tbCompany oCompany = new tbCompany();
        readonly DALAdminLogin theAdminLogin = new DALAdminLogin();
        readonly DALCardType theCardType = new DALCardType();
        readonly DALCard theCard = new DALCard();
        string sApplicatonCardID = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                btnOpenCardApplication.OnClientClick = Grid1.GetNoSelectionAlertInTopReference("没有选中项！");
                btnUpdateCompany.OnClientClick = Grid1.GetNoSelectionAlertInTopReference("没有选中项！");
                btnUpdataStates.OnClientClick = Grid1.GetNoSelectionAlertInTopReference("没有选中项！");

                if (base.CompanyId != null)
                {
                    if (base.CompanyLevelId != "1")
                    {
                        this.ddlUpdateStates.Hidden = true;
                        this.lblUpdateStates.Hidden = true;
                        this.btnUpdataStates.Hidden = true;
                    }
                    //else
                    //{
                    //    this.btnUpdateCompany.Hidden = true;
                    //}
                    this.btnExport.Hidden = true;

                    if (base.AdminTypeId == ((int)EAdminType.Salesman).ToString())
                    {
                        this.lblUpdateCompany.Hidden = true;
                        this.ddlUpdateProvence.Hidden = true;
                        this.ddlUpdateLevel.Hidden = true;
                        this.ddlUpdateCompany.Hidden = true;
                        this.btnUpdateCompany.Hidden = true;
                    }
                }
                else
                {
                    base.ValidateLoginRule(ERule.OpenCardManager);
                    this.btnOpenCardApplication.Hidden = true;
                }
                this.BindCardStates();
                this.BindCardType();
                this.BindProvenctList();
                this.BindCompanyLevel();
                this.BindCompanyListForDown();
                BindGrid();
            }
        }

        void BindCardStates()
        {
            DataSet dsCard = theCard.GetCardStateList();
            this.ddlCardStates.DataTextField = "Name";
            this.ddlCardStates.DataValueField = "Id";
            if (dsCard != null && dsCard.Tables.Count > 0)
            {
                //   dsCard.Tables[0].DefaultView.RowFilter = " Name <> '未发行'";

                this.ddlCardStates.DataSource = dsCard.Tables[0].DefaultView;
                this.ddlCardStates.DataBind();
                this.ddlCardStates.Items.Insert(0, new ExtAspNet.ListItem("请选择...", ""));
                if (!string.IsNullOrEmpty(Request.QueryString["states"]))
                {
                    this.ddlCardStates.SelectedValue = ddlCardStates.Items.FindByValue(Request.QueryString["states"]).Value;
                }
                else
                {
                    this.ddlCardStates.SelectedValue = this.ddlCardStates.Items[0].Value;
                }
            }

            this.ddlUpdateStates.DataTextField = "Name";
            this.ddlUpdateStates.DataValueField = "Id";

            if (dsCard != null && dsCard.Tables.Count > 0)
            {
                if (base.CompanyLevelId == "1")
                {
                    dsCard.Tables[0].DefaultView.RowFilter = " Id = 1 or Id = 2 or Id = 3";
                }
                this.ddlUpdateStates.DataSource = dsCard.Tables[0].DefaultView;
                this.ddlUpdateStates.DataBind();
                this.ddlUpdateStates.SelectedValue = this.ddlUpdateStates.Items[0].Value;
            }

        }

        void BindCardType()
        {
            DataSet dsCardType = theCardType.GetList("1=1");
            this.ddlCardType.DataTextField = "Name";
            this.ddlCardType.DataValueField = "Id";
            this.ddlCardType.DataSource = dsCardType;
            this.ddlCardType.DataBind();
            this.ddlCardType.Items.Insert(0, new ExtAspNet.ListItem("请选择...", ""));
            this.ddlCardType.SelectedValue = this.ddlCardType.Items[0].Value;

        }

        private void BindGrid()
        {   // 1.设置总项数
            Grid1.RecordCount = GetCount();

            DataTable table = GetPagedDataTable(Grid1.PageIndex, Grid1.PageSize, ViewState["sort"] == null ? null: ViewState["sort"].ToString(), ViewState["dir"] == null ? null :ViewState["dir"].ToString() );

            Grid1.DataSource = table;
            Grid1.DataBind();
            Grid1.SelectedRowIndexArray = new int[] {};

        }



        protected void Grid1_PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }



        protected void Grid1_Sort(object sender, ExtAspNet.GridSortEventArgs e)
        {
            DataTable table = GetPagedDataTable(Grid1.PageIndex, Grid1.PageSize,e.SortField,e.SortDirection);
            Grid1.DataSource = table;
            Grid1.DataBind();
            ViewState["sort"] = e.SortField;
            ViewState["dir"] = e.SortDirection;
        }

    

        /// <summary>
        /// 模拟数据库分页
        /// </summary>
        /// <returns></returns>
        private DataTable GetPagedDataTable(int pageIndex, int pageSize,string sort,string sortDir)
        {
            string sql = GetSql(false);
            string sqlSort = "cardcode";
            string sqlSortDir = "asc";
            if (sort != null)
            {
                sqlSort = sort;
            }
            if (sortDir != null)
            {
                sqlSortDir = sortDir;
            }
            sql = string.Format(" SELECT TOP {2} * FROM ( {0} )a   WHERE RowNumber > {2} * ({1})  order by {3} {4}", sql, pageIndex.ToString(), pageSize.ToString(),sqlSort,sqlSortDir);
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            return table;
        }

        string GetSql(bool isCount)
        {
            string sStates = string.Empty;

            if (this.ddlCardStates.SelectedItem.Value != "")
            {
                if (this.ddlCardStates.SelectedItem.Value == "0")
                {
                    sStates = " and states in (0) ";
                    if (this.dpkTimeFrom.Text != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),AddTime,121) >= convert(varchar(10),'{0}',121) ", this.dpkTimeFrom.Text);
                    }
                    if (this.dpkTimeTo.Text != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),AddTime,121) <= convert(varchar(10),'{0}',121) ", this.dpkTimeTo.Text);
                    }
                }
                if (this.ddlCardStates.SelectedItem.Value == "1")
                {
                    sStates = " and states in (1,5) ";
                    if (this.dpkTimeFrom.Text != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),opentime,121) >= convert(varchar(10),'{0}',121) ", this.dpkTimeFrom.Text);
                    }
                    if (this.dpkTimeTo.Text != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),opentime,121) <= convert(varchar(10),'{0}',121) ", this.dpkTimeTo.Text);
                    }
                }
                else if (this.ddlCardStates.SelectedItem.Value == "2")
                {
                    sStates = " and states =2 ";
                    if (this.dpkTimeFrom.Text != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),UsedTime,121) >= convert(varchar(10),'{0}',121) ", this.dpkTimeFrom.Text);
                    }
                    if (this.dpkTimeTo.Text != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),UsedTime,121) <= convert(varchar(10),'{0}',121) ", this.dpkTimeTo.Text);
                    }
                }
                else if (this.ddlCardStates.SelectedItem.Value == "3")
                {
                    sStates = " and states =3 ";
                    if (this.dpkTimeFrom.Text != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),DisableTime,121) >= convert(varchar(10),'{0}',121) ", this.dpkTimeFrom.Text);
                    }
                    if (this.dpkTimeTo.Text != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),DisableTime,121) <= convert(varchar(10),'{0}',121) ", this.dpkTimeTo.Text);
                    }
                }
                else if (this.ddlCardStates.SelectedItem.Value == "4")
                {
                    sStates = " and states =4 ";
                    if (this.dpkTimeFrom.Text != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),AreadyPublishNoOpenTime,121) >= convert(varchar(10),'{0}',121) ", this.dpkTimeFrom.Text);
                    }
                    if (this.dpkTimeTo.Text != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),AreadyPublishNoOpenTime,121) <= convert(varchar(10),'{0}',121) ", this.dpkTimeTo.Text);
                    }
                }
                else if (this.ddlCardStates.SelectedItem.Value == "6")
                {
                    sStates = " and states =6 ";
                    if (this.dpkTimeFrom.Text != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),ApplicationOpenTime,121) >= convert(varchar(10),'{0}',121) ", this.dpkTimeFrom.Text);
                    }
                    if (this.dpkTimeTo.Text != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),ApplicationOpenTime,121) <= convert(varchar(10),'{0}',121) ", this.dpkTimeTo.Text);
                    }
                }
            }

            string sSort = "ORDER BY ";


            string sqlSort = Grid1.SortColumn;
            string sqlSortDir = Grid1.SortDirection;
            if (ViewState["sort"] != null)
            {
                sqlSort = ViewState["sort"].ToString() ;
            }
            if (ViewState["dir"] != null)
            {
                sqlSortDir = ViewState["dir"].ToString();
            }

            sSort = sSort + sqlSort + " " + sqlSortDir;


            string sqlCount = " select count(1)  ";

            string sqlBefor = "select ROW_NUMBER() OVER (" + sSort + ") AS RowNumber,*,(select [name] from tbCardState where Id = db_card.states) as statesName,convert(varchar(10),starttime,121) + ' 至 ' + convert(varchar(10),endtime,121) as exptime, (select Name from tbCardType where Id = DB_Card.CardTypeId) as CardTypeName"
                          + " ,(select CompanyShortName from tbCompany where Id=DB_Card.companyId  ) + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IICompanyId  ),' ') + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IIICompanyId  ),' ') + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IVCompanyId  ),' ') as companyName"
                           + ", case (select top 1 1 from tbGMS where cardid=DB_Card.cardid) when 1 then '已发' else '未发' end as isSend ";


            string sql = " from DB_Card where 1=1 "
                         + sStates;





            if (this.txtCardFrom.Text.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.txtCardFrom.Text.Trim());
                    sql = sql + " and convert(decimal,cardcode) >= " + this.txtCardFrom.Text.Trim() + " ";
                }
                catch
                {

                }
            }
            if (this.txtCardTo.Text.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.txtCardTo.Text.Trim());
                    sql = sql + " and convert(decimal,cardcode) <= " + this.txtCardTo.Text.Trim() + " ";
                }
                catch
                {

                }
            }

            sql = sql + string.Format(" and (companyId={0} or IICompanyId={0} or IIICompanyId={0} or IVCompanyId={0})"
                                       , Request.QueryString["id"]);

            //if (this.ddlProfessionAreaType.SelectedItem.Value != "")
            //{
            //    sql = sql + " and CardTypeId in(select id from tbCardType where ProfessionAreaTypeId = " + this.ddlProfessionAreaType.SelectedItem.Value + ")";
            //}
            if (!string.IsNullOrEmpty(this.ddlCardType.SelectedItem.Value))
            {
                sql = sql + " and CardTypeId = " + this.ddlCardType.SelectedItem.Value;
            }

            sql = sql + " and publishWay='" + this.ddlPublishWay.SelectedItem.Value + "'";

            sql = sql + " and UseWay = " + this.ddlUseWay.SelectedItem.Value;

            if (isCount) return sqlCount + sql;
            else return sqlBefor + sql;


        }


        int  GetCount()
        {
            DataTable dtRowCount = SQLAccess.GreatDs(GetSql(true)).Tables[0];
            if (dtRowCount.Rows.Count > 0)
            {
                return int.Parse(dtRowCount.Rows[0][0].ToString());
            }
            else
            {
                return 0;
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid();
        }

        protected void btnOpenCardApplication_Click(object sender, EventArgs e)
        {
            Hashtable htCardIds = new Hashtable();
            if (string.IsNullOrEmpty(sApplicatonCardID))
            {
                int selectedCount = this.Grid1.SelectedRowIndexArray.Length;
                for (int i = 0; i < selectedCount; i++)
                {
                    int rowIndex = this.Grid1.SelectedRowIndexArray[i];
                    htCardIds.Add(i.ToString(), this.Grid1.DataKeys[rowIndex][0].ToString());
                }
            }
            else
            {
                htCardIds.Add(sApplicatonCardID, sApplicatonCardID);
                sApplicatonCardID = string.Empty;
            }

            //if (htCardIds.Count <= 0)
            //{
            //    ExtAspNet.Alert.Show("您没有选择要开卡的记录！");
            //    return;
            //}

            foreach (string key in htCardIds.Keys)
            {
                if (base.CompanyId != null)
                {
                    string sExeSql = string.Empty;
                    decimal dCompanyMoney = theCompany.GetCompanyMoney(base.CompanyId);
                    decimal dOnSale = theCompany.GetCompanyOnSale(base.CompanyId);
                    if (base.CompanyLevelId == "2")
                    {
                        tbCompany oCompanyII = theCompany.GetModel(int.Parse(base.CompanyId));
                        tbCompany oCompanyI = theCompany.GetModel(oCompanyII.ParentId);
                        decimal dCompanyOnSaleI = theCompany.GetCompanyOnSale(oCompanyI.Id.ToString());
                        decimal dCompanyMoneyI = theCompany.GetCompanyMoney(oCompanyI.Id.ToString());

                        tbCardState oCardState;
                        DB_Card oCard;
                        oCard = theCard.GetModel(int.Parse(htCardIds[key].ToString()));
                        oCardState = theCardState.GetModel(oCard.states);

                        sExeSql = " update db_card set states=6,ApplicationOpenTime='" + DateTime.Now.ToString()
                                + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到申请激活中 ,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                            + ";' where  cardid=" + htCardIds[key] + " and  states !=1 and states !=2"
                                 + ";update DB_Card set states=1,opentime='" + DateTime.Now.ToString() + "'"
                            + ", OpenAdminId = " + base.AdminUserId
                             + ", CompanyOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.CompanyId order by AddDate desc),1)"
                             + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IICompanyId order by AddDate desc),1)"
                             + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IIICompanyId order by AddDate desc),1)"
                             + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IVCompanyId order by AddDate desc),1)"
                             + ",  updatetime='" + DateTime.Now.ToString()
                                + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到审核通过已激活,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                             + "'  where cardprice * 0.5 * " + dOnSale.ToString() + " <= " + dCompanyMoney.ToString()
                             + " and cardprice * 0.5 * " + dCompanyOnSaleI.ToString() + " <= " + dCompanyMoneyI.ToString()
                             + " and cardid=" + htCardIds[key] + " and states !=1 and states !=2";
                    }
                    else if (base.CompanyLevelId == "3")
                    {
                        tbCompany oCompanyIII = theCompany.GetModel(int.Parse(base.CompanyId));
                        tbCompany oCompanyII = theCompany.GetModel(oCompanyIII.ParentId);
                        tbCompany oCompanyI = null;

                        if (oCompanyII.LevelId == 2)
                        {
                            oCompanyI = theCompany.GetModel(oCompanyII.ParentId);
                        }

                        decimal dCompanyOnSaleI = oCompanyI == null ? theCompany.GetCompanyOnSale(oCompanyII.Id.ToString()) : theCompany.GetCompanyOnSale(oCompanyI.Id.ToString());
                        decimal dCompanyMoneyI = oCompanyI == null ? theCompany.GetCompanyMoney(oCompanyII.Id.ToString()) : theCompany.GetCompanyMoney(oCompanyI.Id.ToString());
                        decimal dCompanyOnSaleII = oCompanyI == null ? 0 : theCompany.GetCompanyOnSale(oCompanyII.Id.ToString());
                        decimal dCompanyMoneyII = oCompanyI == null ? 0 : theCompany.GetCompanyMoney(oCompanyII.Id.ToString());


                        tbCardState oCardState;
                        DB_Card oCard;
                        oCard = theCard.GetModel(int.Parse(htCardIds[key].ToString()));
                        oCardState = theCardState.GetModel(oCard.states);

                        sExeSql = " update db_card set states=6,ApplicationOpenTime='" + DateTime.Now.ToString()
                            + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到申请激活中 ,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                            + ";'  where  cardid=" + htCardIds[key] + " and states !=1 and states !=2"
                                 + "; update DB_Card set states=1,opentime='" + DateTime.Now.ToString() + "'"
                                  + ", OpenAdminId = " + base.AdminUserId
                             + ", CompanyOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.CompanyId order by AddDate desc),1)"
                             + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IICompanyId order by AddDate desc),1)"
                             + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IIICompanyId order by AddDate desc),1)"
                             + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IVCompanyId order by AddDate desc),1)"
                             + ",  updatetime='" + DateTime.Now.ToString()
                                + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到审核通过已激活,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                             + "'  where cardprice * 0.5 * " + dOnSale.ToString() + " <= " + dCompanyMoney.ToString()
                             + " and cardprice * 0.5 * " + dCompanyOnSaleI.ToString() + " <= " + dCompanyMoneyI.ToString()
                             + " and cardprice *0.5  * " + dCompanyOnSaleII.ToString() + " <= " + dCompanyMoneyII.ToString()
                             + " and cardid=" + htCardIds[key] + " and states !=1 and states !=2";
                    }
                    else if (base.CompanyLevelId == "4")
                    {
                        tbCompany oCompanyIV = theCompany.GetModel(int.Parse(base.CompanyId));
                        tbCompany oCompanyIII = theCompany.GetModel(oCompanyIV.ParentId);

                        tbCompany oCompanyII = null;
                        tbCompany oCompanyI = null;

                        decimal dCompanyOnSaleI = 0;
                        decimal dCompanyMoneyI = 0;
                        decimal dCompanyOnSaleII = 0;
                        decimal dCompanyMoneyII = 0;
                        decimal dCompanyOnSaleIII = 0;
                        decimal dCompanyMoneyIII = 0;

                        if (oCompanyIII.LevelId == 3)
                        {
                            oCompanyII = theCompany.GetModel(oCompanyIII.ParentId);
                            if (oCompanyII.LevelId == 2)
                            {
                                oCompanyI = theCompany.GetModel(oCompanyII.ParentId);

                                dCompanyOnSaleI = theCompany.GetCompanyOnSale(oCompanyI.Id.ToString());
                                dCompanyMoneyI = theCompany.GetCompanyMoney(oCompanyI.Id.ToString());
                                dCompanyOnSaleII = theCompany.GetCompanyOnSale(oCompanyII.Id.ToString());
                                dCompanyMoneyII = theCompany.GetCompanyMoney(oCompanyII.Id.ToString());
                                dCompanyOnSaleIII = theCompany.GetCompanyOnSale(oCompanyIII.Id.ToString());
                                dCompanyMoneyIII = theCompany.GetCompanyMoney(oCompanyIII.Id.ToString());
                            }
                            else if (oCompanyII.LevelId == 1)
                            {
                                oCompanyI = theCompany.GetModel(oCompanyII.Id);

                                dCompanyOnSaleI = theCompany.GetCompanyOnSale(oCompanyI.Id.ToString());
                                dCompanyMoneyI = theCompany.GetCompanyMoney(oCompanyI.Id.ToString());
                                dCompanyOnSaleII = 0;
                                dCompanyMoneyII = 0;
                                dCompanyOnSaleIII = theCompany.GetCompanyOnSale(oCompanyIII.Id.ToString());
                                dCompanyMoneyIII = theCompany.GetCompanyMoney(oCompanyIII.Id.ToString());
                            }
                        }
                        else if (oCompanyIII.LevelId == 2)
                        {
                            oCompanyII = theCompany.GetModel(oCompanyIII.Id);
                            oCompanyI = theCompany.GetModel(oCompanyII.ParentId);

                            dCompanyOnSaleI = theCompany.GetCompanyOnSale(oCompanyI.Id.ToString());
                            dCompanyMoneyI = theCompany.GetCompanyMoney(oCompanyI.Id.ToString());
                            dCompanyOnSaleII = theCompany.GetCompanyOnSale(oCompanyII.Id.ToString());
                            dCompanyMoneyII = theCompany.GetCompanyMoney(oCompanyII.Id.ToString());
                            dCompanyOnSaleIII = 0;
                            dCompanyMoneyIII = 0;
                        }

                        tbCardState oCardState;
                        DB_Card oCard;
                        oCard = theCard.GetModel(int.Parse(htCardIds[key].ToString()));
                        oCardState = theCardState.GetModel(oCard.states);

                        sExeSql = " update db_card set states=6 " + ",  updatetime='" + DateTime.Now.ToString() + "' ,ApplicationOpenTime='" + DateTime.Now.ToString()
                             + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到申请激活中 ,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                               + ";' where cardid=" + htCardIds[key] + " and states !=1 and states !=2"
                                 + "; update DB_Card set states=1,opentime='" + DateTime.Now.ToString() + "'"
                             + ", OpenAdminId = " + base.AdminUserId
                             + ", CompanyOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.CompanyId order by AddDate desc),1)"
                             + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IICompanyId order by AddDate desc),1)"
                             + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IIICompanyId order by AddDate desc),1)"
                             + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IVCompanyId order by AddDate desc),1)"
                             + ",  updatetime='" + DateTime.Now.ToString()
                             + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到审核通过已激活,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                             + ";'  where cardprice * 0.5 * " + dOnSale.ToString() + " <= " + dCompanyMoney.ToString()
                             + " and cardprice * 0.5 * " + dCompanyOnSaleI.ToString() + " <= " + dCompanyMoneyI.ToString()
                             + " and cardprice * 0.5 * " + dCompanyOnSaleII.ToString() + " <= " + dCompanyMoneyII.ToString()
                             + " and cardprice * 0.5 * " + dCompanyOnSaleIII.ToString() + " <= " + dCompanyMoneyIII.ToString()
                             + " and cardid=" + htCardIds[key] + " and states !=1 and states !=2";
                    }
                    if (!string.IsNullOrEmpty(sExeSql))
                    {
                        SQLAccess.DoSql(sExeSql);
                    }

                }
            }
            ExtAspNet.Alert.Show("激活成功！");
            this.BindGrid();
        }


        void BindProvenctList()
        {
            string sWhere = "";
            if (!string.IsNullOrEmpty(base.CompanyId))
            {
                sWhere = string.Format(" and ( id ={0} or parentId={0})", base.CompanyId);
            }
            DataSet ds = theCompany.GetProvenceList(sWhere);
            this.ddlUpdateProvence.DataTextField = "provence";
            this.ddlUpdateProvence.DataValueField = "provence";
            this.ddlUpdateProvence.DataSource = ds;
            this.ddlUpdateProvence.DataBind();
            this.ddlUpdateProvence.Items.Insert(0, new ExtAspNet.ListItem("请选择省", "-1"));
            this.ddlUpdateProvence.SelectedValue = this.ddlUpdateProvence.Items[0].Value;
        }


        void BindCompanyLevel()
        {
            DataSet ds = theCompany.GetCompanyLevelList();
            if (base.CompanyId != null && base.AdminTypeId != "1")
            {
                ds.Tables[0].DefaultView.RowFilter = " Id >= " + base.CompanyLevelId;
            }
            this.ddlUpdateLevel.DataTextField = "LevelName";
            this.ddlUpdateLevel.DataValueField = "Id";
            this.ddlUpdateLevel.DataSource = ds.Tables[0].DefaultView;
            this.ddlUpdateLevel.DataBind();
            this.ddlUpdateLevel.Items.Insert(0, new ExtAspNet.ListItem("请选择商家级别...", "-1"));
            this.ddlUpdateLevel.SelectedValue = this.ddlUpdateLevel.Items[0].Value;
        }

        protected void ddlUpdateProvence_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindCompanyListForDown();
        }


        void BindCompanyListForDown()
        {
            DataTable dt;
            string sWhere = " 1=1 ";
            dt = theCompany.GetList(sWhere).Tables[0];
            if (base.CompanyId != null)
            {
                dt = GetAllCompany(dt, null, int.Parse(base.CompanyId), true);
            }
            else
            {
                dt = GetAllCompany(dt, null, 0, true);
            }

            string sFiler = string.Empty;
            if (this.ddlUpdateLevel.SelectedItem.Value != "-1")
            {
                sFiler = " LevelID = " + this.ddlUpdateLevel.SelectedItem.Value;
            }
            if (this.ddlUpdateProvence.SelectedItem.Value != "-1")
            {
                sFiler = sFiler == string.Empty ? " Provence = '" + this.ddlUpdateProvence.SelectedItem.Value + "'" : sFiler + " and Provence = '" + this.ddlUpdateProvence.SelectedItem.Value + "'";
            }
            dt.DefaultView.RowFilter = sFiler;

            this.ddlUpdateCompany.DataTextField = "Name";
            this.ddlUpdateCompany.DataValueField = "Id";
            this.ddlUpdateCompany.DataSource = dt.DefaultView;
            this.ddlUpdateCompany.DataBind();
            this.ddlUpdateCompany.Items.Insert(0, new ExtAspNet.ListItem("请选择商家...", "-1"));

        }

        protected void ddlUpdateLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindCompanyListForDown();
        }

        protected void btnUpdateCompany_Click(object sender, EventArgs e)
        {
            if (this.ddlUpdateCompany.SelectedItem.Value != "")
            {
                string companyId = "";
                companyId = this.ddlUpdateCompany.SelectedItem.Value;

                Hashtable htCardIds = new Hashtable();
             
                int selectedCount = this.Grid1.SelectedRowIndexArray.Length;
                for (int i = 0; i < selectedCount; i++)
                {
                    int rowIndex = this.Grid1.SelectedRowIndexArray[i];

                    htCardIds.Add(i.ToString(), this.Grid1.DataKeys[rowIndex][0].ToString());
                }
       
                //if (htCardIds.Count <= 0)
                //{
                //    ExtAspNet.Alert.Show("您没有选中要更新商家的记录！");
                //    return;
                //}

                foreach (string key in htCardIds.Keys)
                {

                    oCompany = theCompany.GetModel(int.Parse(companyId));
                    string sUpdateBefor = string.Empty;
                    string sUpdateSql = string.Empty;

                    decimal companyOnSale = theCompany.GetCompanyOnSale(companyId);

                    if (oCompany.LevelId == 2)
                    {
                        decimal companyOnSaleI = theCompany.GetCompanyOnSale(oCompany.ParentId.ToString());
                        sUpdateSql = "  CompanyId = " + oCompany.ParentId + ", CompanyOnSale=" + companyOnSaleI
                                     + " , IICompanyId = " + companyId + ", CompanyIIOnSale=" + companyOnSale
                                     + ", IIICompanyId = NULL ,CompanyIIIOnSale = 1 "
                                      + ", IVCompanyId = NULL ,CompanyIVOnSale = 1 ";
                    }
                    else if (oCompany.LevelId == 3)
                    {
                        tbCompany companyII = theCompany.GetModel(oCompany.ParentId);
                        if (companyII.LevelId == 2)
                        {
                            decimal companyOnSaleI = theCompany.GetCompanyOnSale(companyII.ParentId.ToString());
                            decimal companyOnSaleII = theCompany.GetCompanyOnSale(oCompany.ParentId.ToString());
                            sUpdateSql = "  CompanyId = " + companyII.ParentId + ", CompanyOnSale=" + companyOnSaleI
                                         + " , IICompanyId = " + companyII.Id + ", CompanyIIOnSale=" + companyOnSaleII
                                         + ", IIICompanyId = " + companyId + ", CompanyIIIOnSale=" + companyOnSale
                                          + ", IVCompanyId = NULL ,CompanyIVOnSale = 1 ";
                        }
                        else if (companyII.LevelId == 1)
                        {
                            decimal companyOnSaleI = theCompany.GetCompanyOnSale(companyII.Id.ToString());

                            sUpdateSql = "  CompanyId = " + companyII.Id + ", CompanyOnSale=" + companyOnSaleI
                                         + " , IICompanyId = NULL, CompanyIIOnSale=1"
                                         + ", IIICompanyId = " + companyId + ", CompanyIIIOnSale=" + companyOnSale
                                          + ", IVCompanyId = NULL ,CompanyIVOnSale = 1 ";
                        }
                    }
                    else if (oCompany.LevelId == 4)
                    {
                        tbCompany companyIII = theCompany.GetModel(oCompany.ParentId);

                        if (companyIII.LevelId == 3)
                        {

                            tbCompany companyII = theCompany.GetModel(companyIII.ParentId);
                            decimal companyOnSaleI = theCompany.GetCompanyOnSale(companyII.ParentId.ToString());
                            decimal companyOnSaleII = theCompany.GetCompanyOnSale(companyIII.ParentId.ToString());
                            decimal companyOnSaleIII = theCompany.GetCompanyOnSale(oCompany.ParentId.ToString());
                            sUpdateSql = "  CompanyId = " + companyII.ParentId + ", CompanyOnSale=" + companyOnSaleI
                                         + ",  IICompanyId = " + companyII.Id + ", CompanyIIOnSale=" + companyOnSaleII
                                         + ", IIICompanyId = " + companyIII.Id + ", CompanyIIIOnSale=" + companyOnSaleIII
                                        + ", IVCompanyId = " + companyId + ", CompanyIVOnSale=" + companyOnSale;
                        }
                        else if (companyIII.LevelId == 2)
                        {

                            tbCompany companyI = theCompany.GetModel(companyIII.ParentId);
                            decimal companyOnSaleI = theCompany.GetCompanyOnSale(companyIII.ParentId.ToString());
                            decimal companyOnSaleII = theCompany.GetCompanyOnSale(companyIII.Id.ToString());

                            sUpdateSql = "  CompanyId = " + companyI.Id + ", CompanyOnSale=" + companyOnSaleI
                                         + ",  IICompanyId = " + companyIII.Id + ", CompanyIIOnSale=" + companyOnSaleII
                                         + ", IIICompanyId = NULL, CompanyIIIOnSale=1"
                                        + ", IVCompanyId = " + companyId + ", CompanyIVOnSale=" + companyOnSale;
                        }
                        else if (companyIII.LevelId == 1)
                        {

                            tbCompany companyI = theCompany.GetModel(companyIII.Id);
                            decimal companyOnSaleI = theCompany.GetCompanyOnSale(companyIII.Id.ToString());

                            sUpdateSql = "  CompanyId = " + companyI.Id + ", CompanyOnSale=" + companyOnSaleI
                                         + ",  IICompanyId = NULL, CompanyIIOnSale=1"
                                         + ", IIICompanyId = NULL, CompanyIIIOnSale=1"
                                        + ", IVCompanyId = " + companyId + ", CompanyIVOnSale=" + companyOnSale;
                        }
                    }
                    else if (string.IsNullOrEmpty(base.CompanyId) || base.CompanyLevelId == "1")
                    {
                        sUpdateSql = "  CompanyId = " + companyId + ", CompanyOnSale=" + companyOnSale
                                       + ", IICompanyId = NULL ,CompanyIIOnSale = 1 "
                                       + ", IIICompanyId = NULL ,CompanyIIIOnSale = 1 "
                                       + ", IVCompanyId = NULL ,CompanyIVOnSale = 1 ";
                    }
                    if (!string.IsNullOrEmpty(base.CompanyId))
                    {
                        if (base.CompanyLevelId == "1")
                        {
                            sUpdateBefor = " IICompanyId = (case when isnull((select Id from tbCompany where ParentId = " + base.CompanyId + " and id=CompanyId),0) = 0  then null else IICompanyId end) "
                                                   + ", IIICompanyId = (case when isnull((select Id from tbCompany where ParentId = " + base.CompanyId + " and id=CompanyId),0) = 0 then null else IIICompanyId end) "
                            + ", IVCompanyId = (case when isnull((select Id from tbCompany where ParentId = " + base.CompanyId + " and id=CompanyId),0) =0 then null else IVCompanyId end) ";
                        }
                        else if (base.CompanyLevelId == "2")
                        {
                            sUpdateBefor = " IIICompanyId = (case when isnull((select Id from tbCompany where ParentId = " + base.CompanyId + " and id=CompanyId),0) = 0 then null else IIICompanyId end) "
                            + ", IVCompanyId = (case when isnull((select Id from tbCompany where ParentId = " + base.CompanyId + " and id=CompanyId),0) =0 then null else IVCompanyId end) ";
                        }
                        else if (base.CompanyLevelId == "3")
                        {
                            sUpdateBefor = " IVCompanyId = (case when isnull((select Id from tbCompany where ParentId = " + base.CompanyId + " and id=CompanyId),0) =0 then null else IVCompanyId end) ";
                        }
                        SQLAccess.DoSql("update DB_Card set " + sUpdateBefor + " where cardid=" + htCardIds[key]);
                    }
                    SQLAccess.DoSql("update DB_Card set " + sUpdateSql + ", states=4,AreadyPublishNoOpenTime='" + DateTime.Now.ToString() + "' where cardid=" + htCardIds[key] + " and states=0;"
                                   + " update DB_Card set " + sUpdateSql + ", remark = isnull(remark,'') +'" + base.AdminUser + " 更新了公司为:" + oCompany.Name + ",时间:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";'   where cardid=" + htCardIds[key]);
                }
                Response.Write("<script language=javascript>alert('批量更新商家成功！');</script>");
                this.BindGrid();
            }
        }

        protected void btnUpdataStates_Click(object sender, EventArgs e)
        {
            DB_Card oCard;

            tbCardState oCardState;
            Hashtable htCardIds = new Hashtable();
            int selectedCount = this.Grid1.SelectedRowIndexArray.Length;
            for (int i = 0; i < selectedCount; i++)
            {
                int rowIndex = this.Grid1.SelectedRowIndexArray[i];

                htCardIds.Add(i.ToString(), this.Grid1.DataKeys[rowIndex][0].ToString());
            }

            //if (htCardIds.Count <= 0)
            //{
            //    ExtAspNet.Alert.Show("您没有选中要更新状态的记录！");
            //    return;
            //}

            string sCardStates = this.ddlUpdateStates.SelectedItem.Value;

            foreach (string key in htCardIds.Keys)
            {
                oCard = theCard.GetModel(int.Parse(htCardIds[key].ToString()));
                oCardState = theCardState.GetModel(oCard.states);
                if (sCardStates == "1")
                {
                    SQLAccess.DoSql("update DB_Card set states=1,opentime='" + DateTime.Now.ToString() + "'," + "OpenAdminid=" + base.AdminUserId
                             + ", CompanyOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.CompanyId order by AddDate desc),1)"
                             + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IICompanyId order by AddDate desc),1)"
                             + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IIICompanyId order by AddDate desc),1)"
                             + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IVCompanyId order by AddDate desc),1)"
                             + ",  updatetime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlUpdateStates.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";'  where cardid=" + htCardIds[key] + " and states!=2 and  states!=1");
                }
                else
                {
                    if (sCardStates == "0")
                    {
                        SQLAccess.DoSql("update DB_Card set states=" + sCardStates + ",  opentime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlUpdateStates.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";' where cardid=" + htCardIds[key] + " and states!=2");
                    }
                    else if (sCardStates == "1")
                    {
                        SQLAccess.DoSql("update DB_Card set states=" + sCardStates + ",  opentime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlUpdateStates.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";' where cardid=" + htCardIds[key] + " and states!=2");
                    }
                    else if (sCardStates == "2")
                    {
                        SQLAccess.DoSql("update DB_Card set states=" + sCardStates + ",  UsedTime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlUpdateStates.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";' where cardid=" + htCardIds[key] + " and states!=2");
                    }
                    else if (sCardStates == "3")
                    {
                        SQLAccess.DoSql("update DB_Card set states=" + sCardStates + ",  DisableTime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlUpdateStates.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";' where cardid=" + htCardIds[key] + " and states!=2");
                    }
                    else if (sCardStates == "4")
                    {
                        SQLAccess.DoSql("update DB_Card set states=" + sCardStates + ",  AreadyPublishNoOpenTime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlUpdateStates.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";' where cardid=" + htCardIds[key] + " and states!=2");
                    }
                    else if (sCardStates == "6")
                    {
                        SQLAccess.DoSql("update DB_Card set states=" + sCardStates + ",  ApplicationOpenTime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlUpdateStates.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";' where cardid=" + htCardIds[key] + " and states!=2");
                    }
                }
            }
            ExtAspNet.Alert.Show("批量更新状态成功！");
            this.BindGrid();

        }

        protected void Grid1_RowCommand(object sender, ExtAspNet.GridCommandEventArgs e)
        {
           
            if (e.CommandName == "open")
            {
                int id = int.Parse(Grid1.DataKeys[e.RowIndex][0].ToString());

                tbCardState oCardState;
                DB_Card oCard;
                oCard = theCard.GetModel(id);
                oCardState = theCardState.GetModel(oCard.states);

                if (base.CompanyId == null || (base.CompanyId != null && base.CompanyLevelId == "1"))
                {
                    SQLAccess.DoSql("update DB_Card set states=1,opentime='" + DateTime.Now.ToString() + "'"
                                 + ", CompanyOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.CompanyId order by AddDate desc),1)"
                                 + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IICompanyId order by AddDate desc),1)"
                                 + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IIICompanyId order by AddDate desc),1)"
                                 + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IVCompanyId order by AddDate desc),1)"
                                  + ",  updatetime='" + DateTime.Now.ToString()
                                 + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到审核通过已激活,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                                 + ";'  where cardid=" + id.ToString() + " and  states!=2");
                    ExtAspNet.Alert.Show("更新状态成功！");
                    this.BindGrid();
                }
                else
                    if (base.CompanyId != null)
                    {
                        sApplicatonCardID = id.ToString();
                        this.btnOpenCardApplication_Click(null, null);
                        //SQLAccess.DoSql("update DB_Card set states = 6,ApplicationOpenTime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到申请激活中 ,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") 
                        //           +";'  where cardid=" + id.ToString() + " and states = 4");
                    }

            }

        }


    }
}